package com.ht.util;

import com.alibaba.fastjson.JSON;
import com.ht.enums.ErrorCode;
import com.ht.model.vo.ResponseVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtil<T> {
    /**
     * 成功响应
     * @param response 响应
     * @param code 状态吗
     * @param msg 提示信息
     * @param data 数据
     * @param <T>泛型
     * @throws IOException Io异常
     */
    public static <T> void success(HttpServletResponse response ,int code, String msg, T data) throws IOException {
        ResponseVO<T> responseVO = new ResponseVO<>(code, msg, data);
        //讲对象转换成JSON字符串
        String json = JSON.toJSONString(response);
        //将JSON字符串写入到响应中
        response.getWriter().write(json);
    }

    /**
     *
     * @param response
     * @param <T>
     * @throws IOException
     */
    public static <T> void fail(HttpServletResponse response)throws IOException{
        success(response,500,"系统异常",null);
    }

    /**
     *
     * @param response
     * @param errorCode
     * @param <T>
     * @throws IOException
     */
    public static <T> void fail(HttpServletResponse response, ErrorCode errorCode) throws IOException {
        success(response,errorCode.getCode(),errorCode.getMsg(),null);
    }
}
